import type { FC } from "react";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Space, Form, Input, message } from "antd";
import { Link, redirect, useSearchParams, useFetcher } from "react-router-dom";
import type { ActionFunctionArgs } from "react-router-dom";
import { loginApi } from "@/api/auth-api.ts";
import to from "await-to-js";
import { setToken } from "@/store/app-store.ts";

const Login: FC = () => {
  // 解析 URL 中的查询参数
  const [searchParams] = useSearchParams();
  const loginFetcher = useFetcher();

  const onFinish = (values: LoginForm) => {
    if (loginFetcher.state === "submitting") return;
    loginFetcher.submit(values, {
      method: "POST",
    });
  };
  return (
    <Form onFinish={onFinish} size="large" initialValues={{ username: searchParams.get("uname") }}>
      <Form.Item
        name="username"
        rules={[
          { required: true, message: "请输入用户名!" },
          {
            pattern: /^[a-zA-Z0-9]{1,10}$/,
            message: "用户名只能是字母和数字，长度1-10",
          },
        ]}
      >
        <Input autoComplete="username" prefix={<UserOutlined />} placeholder="用户名" />
      </Form.Item>
      <Form.Item
        name="password"
        rules={[
          { required: true, message: "请输入密码!" },
          {
            pattern: /^\S{6,15}$/,
            message: "密码必须是6-15位的非空字符",
          },
        ]}
      >
        <Input.Password autoComplete="new-password" prefix={<LockOutlined />} placeholder="密码" />
      </Form.Item>

      <Form.Item>
        <Space direction="vertical">
          <Button type="primary" htmlType="submit" loading={loginFetcher.state === "submitting" && { delay: 200 }}>
            登录
          </Button>
          <div>
            <Link to="/reg">去注册</Link>
          </div>
        </Space>
      </Form.Item>
    </Form>
  );
};

// 定义并导出路由 action 函数
export const action = async ({ request }: ActionFunctionArgs) => {
  const fd = await request.formData();

  // 调用登录的接口
  const [err, res] = await to(loginApi(fd));

  if (err) return null;

  // 登录成功
  // 1.全局存储登录成功之后拿到的 token 值
  // 2.提示用户成功的消息
  // 3.跳转到后台首页
  setToken(res.token);
  message.success(res.message);
  // return redirect("/");
  return null;
};

export default Login;
